﻿using Business.BookManagement;
using Business.BookManagement.Dto;
using Business.Models;
using Business.Permissions;
using System.Linq.Dynamic.Core;
using Business.SupplierManagement.Dto;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Domain.Repositories;
using Volo.Abp.ObjectMapping;
using XCZ;

namespace Business.SupplierManagement
{
    [Authorize(BusinessPermissions.Supplier.Default)]
    public class SupplierAppService : BusinessWorkFlowAppService, ISupplierAppService
    {
        private const string FormName = "Supplier";
        private IRepository<Supplier, Guid> _repository;

        public SupplierAppService(
            IRepository<Supplier, Guid> repository
            )
        {
            _repository = repository;
        }

        #region 增删改查基础方法

        public async Task<SupplierDto> Get(Guid id)
        {
            var data = await _repository.GetAsync(id);
            var dto = ObjectMapper.Map<Supplier, SupplierDto>(data);
            return dto;
        }
        public async Task<PagedResultDto<SupplierDto>> GetAll(GetSupplierInputDto input)
        {
            var query = (await _repository.GetQueryableAsync()).WhereIf(!string.IsNullOrWhiteSpace(input.Filter), a => a.Sname.Contains(input.Filter));

            var totalCount = await query.CountAsync();
            var items = await query.OrderBy(input.Sorting ?? "Id")
                        .ToListAsync();

            var dtos = ObjectMapper.Map<List<Supplier>, List<SupplierDto>>(items);
            return new PagedResultDto<SupplierDto>(totalCount, dtos);
        }

        public async Task<SupplierDto> CreateOrUpdate(CreateOrUpdateSupplierDto input)
        {
            Supplier result = null;
            if (!input.Id.HasValue)
            {
                input.Id = GuidGenerator.Create();
                result = await _repository.InsertAsync(ObjectMapper.Map<CreateOrUpdateSupplierDto, Supplier>(input));

                //创建工作流
                //await WorkFlow.CreateWorkFlow(FormName, result);
            }
            else
            {
                var data = await _repository.GetAsync(input.Id.Value);
                result = await _repository.UpdateAsync(ObjectMapper.Map(input, data));
                //检查流程状态
                // await WorkFlow.CheckFormStatus(input.Id.Value, result);
            }
            return ObjectMapper.Map<Supplier, SupplierDto>(result);
        }

        public async Task Delete(List<Guid> ids)
        {
            foreach (var item in ids)
            {
                await _repository.DeleteAsync(item);
            }

        }
        #endregion
    }
}
